package com.lms.util.WeixinUtil.msg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lms.util.Constants;
import com.lms.util.WeixinUtil.WeixinUtil;
import com.lms.util.WeixinUtil.WeixinConstants;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

public class WeixinPushMsgImpl implements WeixinPushMsg{
    /**
     * 发送模板消息的核心方法
     * @param json 模板消息json格式
     * @return 发送结果
     */
    private int pushMsg(JSONObject json){
        int flag=0;
        String api="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+WeixinUtil.getAccess_token();
        StringBuffer buffer=new StringBuffer();
        try {
            URL url = new URL(api);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setInstanceFollowRedirects(true);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.connect();

            // 将json型的模板消息发送至微信服务器
            OutputStream outputStream = httpUrlConn.getOutputStream();
            outputStream.write(json.toJSONString().getBytes("UTF-8"));// 注意编码格式，防止中文乱码
            outputStream.close();

            // 将微信服务器返回的json输入流转换成字符串，再转为json
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {/*缓冲式读取*/
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            JSONObject resJson = JSON.parseObject(buffer.toString());/*resJson是对于消息是否完成发送的判据*/
            if ("ok".equals(resJson.get("errmsg"))){
                flag = WeixinConstants.SUCCESS;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }
    @Override
    public int push_bindMsg(String openID,String userCode,String template_id) {
        JSONObject json = new JSONObject();
        //构建消息模板
        json.put("touser", openID);
        json.put("template_id", template_id);
        json.put("url", Constants.URL);
        json.put("topcolor", "#FF0000");

        JSONObject dataJson = new JSONObject();
        dataJson.put("keyword1", WeixinUtil.getValue(userCode));
        json.put("data", dataJson);

        return this.pushMsg(json);
    }

    @Override
    public int push_approvalMsg(String openID, String template_id,String labName,String applyCount,String applyTime,boolean res) {
        JSONObject json = new JSONObject();
        //构建消息模板
        json.put("touser", openID);
        json.put("template_id", template_id);
        json.put("url", Constants.URL);
        json.put("topcolor", "#FF0000");

        JSONObject dataJson = new JSONObject();
        dataJson.put("keyword1", WeixinUtil.getValue(labName));
        dataJson.put("keyword2", WeixinUtil.getValue(applyCount));
        dataJson.put("keyword3", WeixinUtil.getValue(applyTime));
        if (res){/*预约成功*/
            dataJson.put("res", WeixinUtil.getValue("预约成功！","#04B90D"));
        }else {/*预约失败*/
            dataJson.put("res", WeixinUtil.getValue("预约失败！","#D80404"));
        }
        json.put("data", dataJson);

        return this.pushMsg(json);
    }

    @Override
    public int push_applyMsg(String openID, String template_id) {
        JSONObject json = new JSONObject();
        //构建消息模板
        json.put("touser", openID);
        json.put("template_id", template_id);
        json.put("url", Constants.URL);
        json.put("topcolor", "#FF0000");

        return this.pushMsg(json);
    }
}
